package com.lagou.edu.request;

import com.lagou.edu.mapper.MapperContext;
import com.lagou.edu.mapper.MapperEngine;
import com.lagou.edu.mapper.MapperHost;
import com.lagou.edu.mapper.MapperWrapper;
import com.lagou.edu.response.Response;
import com.lagou.edu.servlet.HttpServlet;

import java.io.File;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author 赵虎
 * @date 2020/11/9 12:10 上午
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private MapperEngine mapperEngine;

    public RequestProcessor(Socket socket, MapperEngine mapperEngine) {
        this.socket = socket;
        this.mapperEngine = mapperEngine;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            for (MapperHost mapperHost : mapperEngine.getMapperHostList()) {
                if (request.getHost().equals(mapperHost.getName())) {
                    if(request.getUrl().equals("/favicon.ico")){
                        String path = mapperHost.getAppBase() + request.getUrl();
                        response.outputHtml(path);
                    }else {
                        for (MapperContext mapperContext : mapperHost.getMapperContextList()) {
                            if (request.getContext().equals(mapperContext.getName())) {
                                for (MapperWrapper mapperWrapper : mapperContext.getMappedWrapperList()) {
                                    if (mapperWrapper.getUrlPattern().equals(request.getUrl())) {
                                        HttpServlet httpServlet = mapperWrapper.getHttpServlet();
                                        httpServlet.service(request, response);
                                    } else {
                                        String path = mapperHost.getAppBase() + File.separator + request.getContext() + request.getUrl();
                                        response.outputHtml(path);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
